package com.yakaten.service;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.IOUtils;
import org.seasar.framework.log.Logger;
import org.seasar.framework.util.ResourceUtil;

import com.yakaten.exception.MakeShopException;
import com.yakaten.login.MakeShopLogin;
import com.yakaten.utils.HtmlDecoder;

public class MakeShopItemService {

	static Logger logger = Logger.getLogger(MakeShopItemService.class);

	private static final String REGEX_FROM1 = "<form name=form1(.+?)</form>";
	private static final Pattern PATTERN_FROM1 = Pattern.compile(REGEX_FROM1);

	private static final String REGEX_INPUT = "<input(.+?)>";
	private static final Pattern PATTERN_INPUT = Pattern.compile(REGEX_INPUT);

	private static final String REGEX_INPUT_TYPE = "type=[\"|']{0,1}(.+?)[\"|']{0,1} ";
	private static final Pattern PATTERN_INPUT_TYPE = Pattern
			.compile(REGEX_INPUT_TYPE);

	private static final String REGEX_INPUT_NAME = "name=[\"|']{0,1}(.+?)[\"|']{0,1}[ |>]{1}";
	private static final Pattern PATTERN_INPUT_NAME = Pattern
			.compile(REGEX_INPUT_NAME);

	private static final String REGEX_INPUT_VALUE = "value=[\"|']{1}(.*?)[\"|']{1}";
	private static final Pattern PATTERN_INPUT_VALUE = Pattern
			.compile(REGEX_INPUT_VALUE);

	private static final String REGEX_INPUT_CHECKED = "checked";
	private static final Pattern PATTERN_INPUT_CHECKED = Pattern
			.compile(REGEX_INPUT_CHECKED);

	private static final String REGEX_SELECT = "<select(.+?)</select>";
	private static final Pattern PATTERN_SELECT = Pattern.compile(REGEX_SELECT);

	private static final String REGEX_OPTION = "<option(.+?)>";
	private static final Pattern PATTERN_OPTION = Pattern.compile(REGEX_OPTION);

	private static final String REGEX_INPUT_SELECTED = "selected";
	private static final Pattern PATTERN_INPUT_SELECTED = Pattern
			.compile(REGEX_INPUT_SELECTED);

	private static final String REGEX_TEXTAREA = "<textarea(.+?)</textarea>";
	private static final Pattern PATTERN_TEXTAREA = Pattern
			.compile(REGEX_TEXTAREA);

	private static final String REGEX_TEXTAREA_VALUE = "<textarea(.+?)>(.+?)</textarea>";
	private static final Pattern PATTERN_TEXTAREA_VALUE = Pattern
			.compile(REGEX_TEXTAREA_VALUE);

	//<h3 id="itemName">[展示品]SONY VAIO Duo 13 SVD13219CJB [ブラック]</h3>
	private static final String REGEX_HTML_ITEMNAME = "<h3 id=\"itemName\">(.+?)</h3>";
	private static final Pattern PATTERN_HTML_ITEMNAME = Pattern.compile(REGEX_HTML_ITEMNAME);

	//<span id="taxPrice">113,480</span>
	private static final String REGEX_HTML_ITEMPRICE = "<span id=\"taxPrice\">(.+?)</span>";
	private static final Pattern PATTERN_HTML_ITEMPRICE = Pattern.compile(REGEX_HTML_ITEMPRICE);

	protected static final DecimalFormat PRICE_FORMAT = new DecimalFormat("###,###.###");

	public Map<String, String> getItemInfoByHtml(String brcode) throws MakeShopException {
		Map<String, String> resultMap = new HashMap<String, String>();

		String HOST = ResourceUtil.getProperties("yakaten.properties").getProperty("makeshop.host");
		String url = HOST + "smartphone/detail.html?id=" + brcode;

		BufferedReader bufferedReader = null;
		HttpURLConnection connection = null;
		try {
			URL loginUrl = new URL(url);
			connection = (HttpURLConnection) loginUrl.openConnection();
			connection
			.setRequestProperty(
					"User-Agent",
					"Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3");
			connection.connect();

			InputStream urlStream = connection.getInputStream();
			bufferedReader = new BufferedReader(new InputStreamReader(
					urlStream, "euc-jp"));
			String ss = null;
			StringBuffer htmlBuffer = new StringBuffer();
			while ((ss = bufferedReader.readLine()) != null) {
				htmlBuffer.append(ss);
			}

			if (htmlBuffer != null) {

				Matcher matcherItemName = PATTERN_HTML_ITEMNAME.matcher(htmlBuffer);
				String itemName ="";
				if (matcherItemName.find()) {
					itemName =matcherItemName.group(1);
					resultMap.put("itemName", itemName);
				}

				Matcher matcherItemPrice = PATTERN_HTML_ITEMPRICE.matcher(htmlBuffer);
				if (matcherItemPrice.find()) {
					resultMap.put("itemPrice", ""+PRICE_FORMAT.parse(matcherItemPrice.group(1)).longValue());
				}
			}
		} catch (MalformedURLException e) {
			throw new MakeShopException(e);
		} catch (IOException e) {
			throw new MakeShopException(e);
		} catch (ParseException e) {
			throw new MakeShopException(e);
		} finally {
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (connection != null) {
				connection.disconnect();
			}
		}
		return resultMap;
	}


	public Map<String, String> getItemInfo(String brcode)
			throws MakeShopException {

		Map<String, String> resultMap = new IdentityHashMap<String, String>();
		// 005010000009
		String xcode = brcode.substring(0, 3);
		String mcode = brcode.substring(3, 6);

		OutputStreamWriter out = null;
		BufferedReader bufferedReader = null;
		HttpURLConnection connection = null;
		try {

			String ITEM_INFO_URL=ResourceUtil.getProperties("yakaten.properties").getProperty("makeshop.iteminfo.url");
			URL loginUrl = new URL(ITEM_INFO_URL);

			connection = (HttpURLConnection) loginUrl.openConnection();

			connection.setDoOutput(true);

			out = new OutputStreamWriter(connection.getOutputStream(), "euc-jp");

			out.write("xcode=" + xcode + "&mcode=" + mcode + "&brcode="
					+ brcode);

			out.flush();

			InputStream urlStream = connection.getInputStream();
			bufferedReader = new BufferedReader(new InputStreamReader(
					urlStream, "euc-jp"));
			String ss = null;
			StringBuffer total = new StringBuffer();
			while ((ss = bufferedReader.readLine()) != null) {
				total.append(ss);
			}

			if("1".equals(ResourceUtil.getProperties("yakaten.properties").getProperty(
					"makeshop.debug.on"))){
				IOUtils.write(total, new FileOutputStream("/var/www/vhosts/00_default/user/makeshopiteminfo.html"),"shift_jis");
			}
			if (logger.isDebugEnabled()) {
				logger.debug(total);
			}

			Matcher matcherForm1 = PATTERN_FROM1.matcher(total);
			if (matcherForm1.find()) {
				String form1 = matcherForm1.group(1);
				// input
				Matcher matcherInput = PATTERN_INPUT.matcher(form1);
				while (matcherInput.find()) {
					String input = matcherInput.group(1);
					// // type
					String type = "text";
					Matcher matcherInputType = PATTERN_INPUT_TYPE
							.matcher(input);
					if (matcherInputType.find()) {
						type = matcherInputType.group(1);
					}
					if ("button".equals(type.toLowerCase())
							|| "file".equals(type.toLowerCase())) {
						continue;
					}

					if ("radio".equals(type.toLowerCase())
							|| "checkbox".equals(type.toLowerCase())) {
						Matcher matcherInputChecked = PATTERN_INPUT_CHECKED
								.matcher(input);
						if (!matcherInputChecked.find()) {
							continue;
						}
					}

					String name = "";
					Matcher matcherInputName = PATTERN_INPUT_NAME
							.matcher(input);
					if (matcherInputName.find()) {
						name = matcherInputName.group(1);
					}
					if (name.length() <= 0 ) {
						continue;
					}

					String value = "";
					Matcher matcherInputValue = PATTERN_INPUT_VALUE
							.matcher(input);
					if (matcherInputValue.find()) {
						value = matcherInputValue.group(1);
					}

					value = HtmlDecoder.decode(value);
					if (name.length() > 0) {
						if("sellprice".equals(name)){
							resultMap.put(new String("sellpriceMoto"), value);
						}else{
							resultMap.put(new String(name), value);
						}

					}
				}

				// select
				Matcher matcherSelect = PATTERN_SELECT.matcher(form1);

				while (matcherSelect.find()) {
					String select = matcherSelect.group(1);
					String name = "";
					Matcher matcherInputName = PATTERN_INPUT_NAME
							.matcher(select);
					if (matcherInputName.find()) {
						name = matcherInputName.group(1);
					}

					String value = "";
					Matcher matcherOption = PATTERN_OPTION.matcher(select);
					boolean selected = false;
					List<String> workList = new ArrayList<String>();
					while (matcherOption.find()) {
						String option = matcherOption.group(1);
						String workValue = "";
						Matcher matcherInputValue = PATTERN_INPUT_VALUE
								.matcher(option);
						if (matcherInputValue.find()) {
							workValue = matcherInputValue.group(1);
						}
						workList.add(workValue);
						Matcher matcherInputSelected = PATTERN_INPUT_SELECTED
								.matcher(option);
						if (matcherInputSelected.find()) {
							selected = true;
							break;
						}

					}

					if (selected) {
						value = workList.get(workList.size() - 1);
					} else {
						value = workList.get(0);
					}
					if (name.length() > 0) {
						resultMap.put(new String(name), value);
					}
				}

				Matcher matcherTextarea = PATTERN_TEXTAREA.matcher(total);

				while (matcherTextarea.find()) {
					String textarea = matcherTextarea.group(0);
					String name = "";
					Matcher matcherInputName = PATTERN_INPUT_NAME
							.matcher(textarea);
					if (matcherInputName.find()) {
						name = matcherInputName.group(1);
					}

					Matcher matcherValue = PATTERN_TEXTAREA_VALUE
							.matcher(textarea);
					String value = "";
					if (matcherValue.find()) {
						value = matcherValue.group(2);
					}
					value = HtmlDecoder.decode(value);
					if (name.length() > 0) {
						resultMap.put(name, value);
					}
				}
			}

		} catch (MalformedURLException e) {
			throw new MakeShopException(e);
		} catch (IOException e) {
			throw new MakeShopException(e);
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (connection != null) {
				connection.disconnect();
			}
		}

		return resultMap;
	}

	public boolean updateItemInfo(Map<String, String> valueMap)
			throws MakeShopException {
		OutputStreamWriter out = null;
		HttpURLConnection connection = null;
		BufferedReader bufferedReader = null;
		boolean result =false;
		try {
			String ITEM_UPDATE_URL=ResourceUtil.getProperties("yakaten.properties").getProperty("makeshop.itemupdate.url");
			URL updateUrl = new URL(ITEM_UPDATE_URL);
			connection = (HttpURLConnection) updateUrl.openConnection();

			connection.setDoOutput(true);

			out = new OutputStreamWriter(connection.getOutputStream(), "euc-jp");

			StringBuffer para = new StringBuffer();

			Iterator<String> keyIt = valueMap.keySet().iterator();
			while (keyIt.hasNext()) {
				String key = keyIt.next();
				String value = valueMap.get(key);
				para.append(key + "=" + value + "&");
			}

			out.write(para.toString());
			out.flush();

			InputStream urlStream = connection.getInputStream();
			bufferedReader = new BufferedReader(new InputStreamReader(
					urlStream, "euc-jp"));
			String ss = null;
			StringBuffer total = new StringBuffer();
			while ((ss = bufferedReader.readLine()) != null) {
				total.append(ss);
			}

			if("1".equals(ResourceUtil.getProperties("yakaten.properties").getProperty(
					"makeshop.debug.on"))){
				IOUtils.write(total, new FileOutputStream("/var/www/vhosts/00_default/user/makeshopupdateiteminfo.html"),"shift_jis");
			}

			if(total.indexOf("以下の商品を修正しました")>-1){
				if (logger.isDebugEnabled()) {
					logger.debug(total);
				}
				result =true;

			}

		} catch (MalformedURLException e) {
			throw new MakeShopException(e);
		} catch (IOException e) {
			throw new MakeShopException(e);
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (connection != null) {
				connection.disconnect();
			}
		}
		return result;
	}

	public String getBrandName(Map<String, String> valueMap){

		Iterator<String> it = valueMap.keySet().iterator();
		String brandname = null;
		while (it.hasNext()) {
			String key = it.next();
			if (key.equals("brandname")) {
				brandname = key;
			}
		}
		return valueMap.get(brandname);
	}

	public String getSellPriceMoto(Map<String, String> valueMap){
		Iterator<String> it = valueMap.keySet().iterator();
		String sellpriceMoto = null;
		while (it.hasNext()) {
			String key = it.next();
			if (key.equals("sellpriceMoto")) {
				sellpriceMoto = key;
			}
		}
		return  valueMap.get(sellpriceMoto);
	}

	public String getQuantity(Map<String, String> valueMap){
		Iterator<String> it = valueMap.keySet().iterator();
		String checkquantityKey = null;
		String quantity_beforeKey = null;
		while (it.hasNext()) {
			String key = it.next();
			if(key.equals("checkquantity")){
				checkquantityKey =key;
			}
			if(key.equals("quantity_before")){
				quantity_beforeKey =key;
			}
		}
		String checkquantity = valueMap.get(checkquantityKey);
		String quantity ="";
		if("E".equals(checkquantity)){
			quantity = "品切れ";
		}else if("F".equals(checkquantity)){
			quantity = "無制限";
		}else if("C".equals(checkquantity)){
			quantity = valueMap.get(quantity_beforeKey);
		}
		return quantity;
	}

	public static void main(String[] args) {

		try {
//			System.getProperties().put("proxySet", "true");
//
//			System.getProperties().put("proxyPort", "80");
//
//			System.getProperties().put("proxyHost", "proxysv");

			MakeShopLogin login = new MakeShopLogin();
			login.doLogin("ryumei", "andybest123");
			MakeShopItemService service = new MakeShopItemService();
			Map<String, String> valueMap;
			valueMap = service.getItemInfo("026000000001");
//			valueMap.put("type", "upd");
//			valueMap.put(new String("sellprice"), "444");
//			System.out.println(service.updateItemInfo(valueMap));
//			Iterator<String> it = valueMap.keySet().iterator();
//			String brandname =null;
//			String sellpriceMoto=null;
//			String checkquantity = null;
//			String quantity_before = null;
//			while(it.hasNext()){
//				String key =it.next();
//				if(key.equals("brandname")){
//					brandname =key;
//				}
//				if(key.equals("sellpriceMoto")){
//					sellpriceMoto =key;
//				}
//				if(key.equals("checkquantity")){
//					checkquantity =key;
//				}
//				if(key.equals("quantity_before")){
//					quantity_before =key;
//				}
//			}
//
//			Map itemInfo = service.getItemInfoByHtml("000000003700");
//			System.out.println(itemInfo.get("itemName")+","+itemInfo.get("itemPrice"));
////			System.out.println(valueMap.get(checkquantity));
////			System.out.println(valueMap.get(quantity_before));
		} catch (MakeShopException e) {
			e.printStackTrace();
		}
//		System.out.println(Integer.parseInt(""));
	}
}
